package com.webside.subject.controller;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.mock.MockParameterMetaData.Parameter;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.webside.base.basecontroller.BaseController;
import com.webside.dtgrid.model.Pager;
import com.webside.dtgrid.util.ExportUtils;
import com.webside.exception.AjaxException;
import com.webside.exception.ServiceException;
import com.webside.exception.SystemException;
import com.webside.playbackstatistics.service.DictionaryService;
import com.webside.series.model.Bdictionary;
import com.webside.series.service.SeriesService;
import com.webside.subject.model.SubjectEntity;
import com.webside.subject.model.SubjectSeriesEntity;
import com.webside.subject.service.SubjectSeriesService;
import com.webside.subject.service.SubjectService;
import com.webside.util.Common;
import com.webside.util.PageUtil;

@Controller
@Scope("prototype")
@RequestMapping("/subject/")
public class SubjectController extends BaseController {
	@Autowired
	private SubjectService subjectService;
	@Autowired
	private SubjectSeriesService subjectseriesService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private SeriesService seriesService;
	@RequestMapping("listUI.html")
	public String listUI(Model model, HttpServletRequest request) {
		try
		{
			PageUtil page = new PageUtil();
			if(request.getParameterMap().containsKey("page")){
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			}
			model.addAttribute("page", page);
			return Common.BACKGROUND_PATH + "/subject/subjectList";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	/**
	 * ajax分页动态加载模式
	 * @param dtGridPager Pager对象
	 * @throws Exception
	 */
	@RequestMapping(value = "/list.html", method = RequestMethod.POST)
	@ResponseBody
	public Object list(Model model, String gridPager,Bdictionary channel,SubjectEntity subjectEntity, HttpServletResponse response) throws Exception{
		
		Map<String, Object> parameters = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(gridPager, Pager.class);
		// 判断是否包含自定义参数
		parameters = pager.getParameters();
		if (parameters.size() < 0) {
			parameters.put("name", null);
		}
		//3、判断是否是导出操作
		if(pager.getIsExport())
		{
			if(pager.getExportAllData())
			{
				//3.1、导出全部数据
				List<SubjectEntity> list = subjectService.queryListByPage(parameters);
				ExportUtils.exportAll(response, pager, list);
				return null;
			}else
			{
				//3.2、导出当前页数据
				ExportUtils.export(response, pager);
				return null;
			}
		}else
		{
			
			// 设置分页，page里面包含了分页信息
			Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize());
			List<SubjectEntity> list = subjectService.queryListByPage(parameters);
			 
			parameters.clear();
			parameters.put("isSuccess", Boolean.TRUE);
			parameters.put("nowPage", pager.getNowPage());
			parameters.put("pageSize", pager.getPageSize());
			parameters.put("pageCount", page.getPages());
			parameters.put("recordCount", page.getTotal());
			parameters.put("startRecord", page.getStartRow());
			parameters.put("exhibitDatas", list);
			return parameters;
		}
		
	}
	//添加显示
	@RequestMapping("addUI.html")
	public String addUI(Model model, HttpServletRequest request) {
		List<Bdictionary> templateList =  dictionaryService.dictionaryList("TEMPLATE_KIND", "");
		model.addAttribute("templateList", templateList);
		SubjectEntity subject = new SubjectEntity();
		subject.setSubjectName("new");
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);
		subject.setCreateTime(currentTime_2);
		subjectService.addSubject(subject);
		SubjectEntity subject1 = subjectService.selectSubjectBySubject(subject); 
		model.addAttribute("subjectId",subject1.getId());
		return Common.BACKGROUND_PATH + "/subject/form";
	}
	@RequestMapping(value = "add.html", method = RequestMethod.POST)
	@ResponseBody
	public Object add(Model model,SubjectEntity subject, HttpServletRequest request) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{	
			String sid =  request.getParameter("adsubjectId");
			int s=  Integer.parseInt(sid, 10);
			subject.setId(s);
			int count=subjectService.updateAddSubject(subject);
			 
			if(count >0 )
			{
				map.put("success", Boolean.TRUE);
				map.put("data", null);
				map.put("message", "添加成功");
			}else
			{
				map.put("success", Boolean.FALSE);
				map.put("data", null);
				map.put("message", "添加失败");
			}
		}catch(ServiceException e)
		{
			throw new AjaxException(e);
		}
		return map;
	}
	//修改显示
	@RequestMapping("editUI.html")
	public String editUI(Model model, HttpServletRequest request, Long id) {
		
		try
		{
			/*Bdictionary channel=new Bdictionary();
			List<Bdictionary>Type_List=subjectService.selectTypeByAll(channel);
			model.addAttribute("Type_List", Type_List);
			Bdictionary dictionary=serieskindService.findById(id);*/
			PageUtil page = new PageUtil();
			page.setPageNum(Integer.valueOf(request.getParameter("page")));
			page.setPageSize(Integer.valueOf(request.getParameter("rows")));
			page.setOrderByColumn(request.getParameter("sidx"));
			page.setOrderByType(request.getParameter("sord"));
		
			model.addAttribute("page", page);
			/*model.addAttribute("bdictionary", dictionary);*/
			List<Bdictionary> templateList =  dictionaryService.dictionaryList("TEMPLATE_KIND", "");
			model.addAttribute("templateList", templateList);
			Map<String,Object> paramter = new HashMap<>();
			paramter.put("subjectId", id);
			List<SubjectEntity> subjectList = subjectService.selectSubjectByMap(paramter);
			model.addAttribute("subject", subjectList.get(0));

			return Common.BACKGROUND_PATH + "/subject/form";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	//修改
	@RequestMapping("edit.html")
	@ResponseBody
	public Object update(SubjectEntity subject)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		
		try
		 {  	 
				
				int result = subjectService.updateSubject(subject);
				System.out.println(result);
			if(result >0)
			{
				map.put("success", Boolean.TRUE);
				map.put("data", null);
				map.put("message", "编辑成功");
				
			}else
			{
				map.put("success", Boolean.FALSE);
				map.put("data", null);
				map.put("message", "编辑失败");
			}
		}catch(Exception e)
		{
			throw new AjaxException(e);
		}
		return map;
	}
	/**
	 * 资源弹出
	 * @param model
	 * @param code
	 * @return
	 */
	@RequestMapping("SeriesResources.html")
	public String resources(Model model,int subjectId) {
		System.out.println(subjectId+"=================");
		Map parameters = new HashMap<>();
		PageUtil ssListPageUtil =new PageUtil();
		ssListPageUtil.setPageNum(0);
		ssListPageUtil.setPageSize(15);
		List<SubjectSeriesEntity> ssList = null;
		parameters.put("subjectId", subjectId);
		ssList =subjectseriesService.queryListBySubjectId(parameters);
		model.addAttribute("subjectId",subjectId);
		model.addAttribute("seriesBySubjectList",ssList);
		PageUtil pageUtil =new PageUtil();
		pageUtil.setPageNum(0);
		pageUtil.setPageSize(15);
		List<HashMap<String,Object>> list=seriesService.querySeries(pageUtil, "","");
		/*if(list.size()>0){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<String> datelist=new ArrayList<String>();
			for(int i=0;i<list.size();i++){
				String edate=format.format(list.get(i).get("end_date"));
				datelist.add(edate);
			}
			model.addAttribute("datelist",datelist);
		}*/
		model.addAttribute("seriesResourceList",list);
		int SeriesCount = seriesService.countAll();
		model.addAttribute("seriesCount",SeriesCount);
		int count = SeriesCount;
		int totalPageCount;
		if(count>15 ){
			totalPageCount=count/15;
			 if(count%15==0){
				 model.addAttribute("totalPageCount", totalPageCount);
				  
				}else{
					model.addAttribute("totalPageCount", totalPageCount+1);}
		}else{
			totalPageCount=0;
			model.addAttribute("totalPageCount", totalPageCount);
		}
		
		System.out.println("剧集数："+count);
		return Common.BACKGROUND_PATH + "/subject/seriesResources";
	}
	/**
	 * 资源页翻页查询
	 * @param model
	 * @param pSize
	 * @param pageNo
	 * @param sort
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/searchPage.html", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object searchPage(Model model, String pSize,String pageNo,String sort,String code){
		PageUtil pageUtil =new PageUtil();
		int no=Integer.parseInt(pageNo)-1;
		pageUtil.setPageNum(no*Integer.parseInt(pSize));
		pageUtil.setPageSize(Integer.parseInt(pSize));
		int totalPageCount;
		int count=seriesService.countAll();
		if(count>15 ){
			totalPageCount=count/15;
			 if(count%15==0){
				 model.addAttribute("totalPageCount", totalPageCount);
				  
				}else{
					model.addAttribute("totalPageCount", totalPageCount+1);}
		}else{
			totalPageCount=0;
			model.addAttribute("totalPageCount", totalPageCount);
		}
		if(sort==null){
			sort="";
		}
		
		List<HashMap<String, Object>> list=seriesService.querySeries(pageUtil, sort,code);
		return list;
	}
	/**
	 * 资源页收录视频
	 * @param model
	 * @param pSize
	 * @param pageNo
	 * @param sort
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/addIn.html", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public List<SubjectSeriesEntity> addSubjectSeries(Model model, int subjectId,int seriesId){
		SubjectSeriesEntity subjectseries = new SubjectSeriesEntity();
		subjectseries.setSeriesId(seriesId);
		subjectseries.setSubjectId(subjectId);
		SubjectSeriesEntity subjectseries2 = subjectseriesService.selectBySubjectSeries(subjectseries);
		if(subjectseries2==null){
			subjectseriesService.add(subjectseries);
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("subjectId", subjectId);
			 List<SubjectSeriesEntity> slist = subjectseriesService.queryListBySubjectId(parameters);
			 parameters.put("seriesCount", slist.size());
			 subjectService.updateSubjectByMap(parameters);
			return slist;
		}else{
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("subjectId", subjectId);
			 List<SubjectSeriesEntity> slist = subjectseriesService.queryListBySubjectId(parameters);
			return slist;
		}
		
	}
	/**
	 * 资源页收录视频
	 * @param model
	 * @param pSize
	 * @param pageNo
	 * @param sort
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/clean.html", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public int cleanSubjectSeries(Model model, int subjectSeriesId){
		SubjectSeriesEntity subjectseries = new SubjectSeriesEntity();
		subjectseries.setSubjectSeriesId(subjectSeriesId);
		SubjectSeriesEntity subjectseries2 = subjectseriesService.selectBySubjectSeries(subjectseries);
		if(subjectseries2==null){
			
			return 0;
		}else{
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("subjectSeriesId", subjectSeriesId);
			  subjectseriesService.deletesub(subjectseries2);
			 List<SubjectSeriesEntity> ssList = subjectseriesService.queryListBySubjectId(parameters);
			 if(ssList.size()<=0){
				 parameters.put("seriesCount", 0 );
				 subjectService.updateSubjectByMap(parameters);
				 return 1;
			 }
			  parameters.put("subjectId", ssList.get(0).getSubjectId());
			  List<SubjectEntity> slist = subjectService.selectSubjectByMap(parameters);
			  parameters.put("seriesCount", slist.get(0).getSeriesCount() -1 );
				 subjectService.updateSubjectByMap(parameters);
			return 1;
		}
		
	}
	/**
	 * 显示绑定列表
	 * @param model
	 * @param pSize
	 * @param pageNo
	 * @param sort
	 * @param code
	 * @return
	 *//*
	@RequestMapping(value="/showsubjectSeriesList.html", method={RequestMethod.GET,RequestMethod.POST})
	public String showSubjectSeries(Model model, int subjectId){
		HashMap<String, Object> parameters = new HashMap<>();
		parameters.put("subjectId", subjectId);
		List<SubjectSeriesEntity> subjectseries2 = subjectseriesService.queryListByPage(parameters);
		return Common.BACKGROUND_PATH + "/subject/seriesResources";
		
	}*/
}
